#!/usr/bin/env python3
# Copyright (c) 2018 Milis Linux
# Author: milisarge <milisarge@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; If not, see <http://www.gnu.org/licenses/>.

from urllib.parse import urlparse
import base64, json
from opendht import *
import opendht as dht
import threading, time
from random import randint
import sys
import hashlib

class Dht():
	
	def __init__(self,port=None,bs=None):
		self.sunucu_isim="d-acid_sunucu"
		if bs is None:
			self.sunucu="bootstrap.ring.cx:4222"
		else:
			self.sunucu=bs
		self.id = Identity()
		self.id.generate()
		self.node = DhtRunner()
		if port is None:
			port=randint(60000,65000)
		self.node.run(self.id, port=port)
		
		bss=self.sunucu.split(":")[0]
		bsp=self.sunucu.split(":")[1]
		self.node.bootstrap(bss,bsp)

	def hash_al(self,anahtar):
		sha1 = hashlib.sha1()
		sha1.update(anahtar.encode())
		anahtar_hash=sha1.hexdigest()
		return anahtar_hash
		
	def kayit_edildi(self):
		time.sleep(10)
		print ("--------")
		
	def sunucu_kayit(self,deger,anahtar=None):
		#ahash=self.hash_al(anahtar)
		if anahtar is None:
			anahtar=self.sunucu_isim
		time.sleep(1)
		#sonuc=self.node.put(dht.InfoHash.get(anahtar),dht.Value(deger.encode()),self.kayit_edildi())
		sonuc=self.node.put(dht.InfoHash.get(anahtar),dht.Value(deger.encode()))
		#dht dugumunu durdurmak için
		self.node=None
		return sonuc

	def sunucular(self,anahtar=None):
		liste=[]
		#arama saniyesi
		arasn=10
		print ("(%s) altında %s saniye arama yapılacak!" % (self.sunucu,arasn))
		if anahtar is None:
			anahtar=self.sunucu_isim
		bitis = 1
		while bitis > 0:
			bitis += 1
			veriler=(self.node.get(InfoHash.get(anahtar)))
			for veri in veriler:
				sunbilgi=(veri.data).decode('ascii')
				if sunbilgi not in liste:
					liste.append(sunbilgi)
					print (len(liste)," adet kayıt bulundu.",sunbilgi)
			time.sleep(1)
			if bitis == arasn:
				print ("dht sunucu tarama sonlandırıldı.")
				break
		return liste
